package arrAndstr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
    199. 二叉树的右视图
    map记录每层是否访问过
    教训：
        尽量不要使用静态变量 --> 会共享到
 */
public class T199 {


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    // 不要使用静态变量，可能不安全
//    private static Map<Integer, Boolean> map = new HashMap<>();

    public static List<Integer> rightSideView(TreeNode root) {
        Map<Integer, Boolean> map = new HashMap<>();
        return rightView(root, 1, map);
    }

    private static List<Integer> rightView(TreeNode root, int level, Map<Integer, Boolean> map) {
        List<Integer> list = new ArrayList<>();

        if (root == null)   return list;

        if (!map.containsKey(level)) {
            list.add(root.val);
            map.put(level, true);
        }

        list.addAll(rightView(root.right, level+1, map));
        list.addAll(rightView(root.left, level+1, map));
        return list;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.left.left = new TreeNode(4);
        node.left.left.left = new TreeNode(5);
        node.right = new TreeNode(3);

        System.out.println(rightSideView(node));
    }

}
